require 'permission_error'

# filter for access controll 
# requires a #current_user method
#
# will 
#
ActionController::Base.around_filter do |controller, action|
  begin
    # yield the action..
    # catch and authorize any auth_requests
    #
    if auth_request = catch(:auth_request){action.call; nil}
      # check permissions and continue
      auth_request.continue_with_user(controller.current_user)      
    end
  rescue PermissionError => ex
    # render the error / login form to user
    #
    controller.render_permission_error(ex)
  end
end


# methods for rendering login form and permission errrors
#
module ActionController
  module AccessActions
    
    def render_permission_error(exception)
      erase_render_results
      flash[:error] = exception.message
      render :action => 'login_form'
      headers["Status"] = "401 Unauthorized"
      #controller.headers["WWW-Authenticate"] = 'WebBased realm="domain.com"'
    end
    
  end
end

# include new methods onto base
ActionController::Base.send :include, ActionController::AccessActions
